/**
 * MooFlow - Image gallery
 *
 * Dependencies: MooTools 1.2
 *
 * @version			0.2.1
 *
 * @license			MIT-style license
 * @author			Tobias Wetzel <info [at] outcut.de>
 * @copyright		Author
 * @docmentation	http://outcut.de/MooFlow/Docmentation.html
 */ 

var ImageWall = new Class({

	Implements: [Events, Options],
	
	options: {
		onStart: $empty,
		onClickView: $empty,
		onAutoPlay: $empty,
		onAutoStop: $empty,
		onRequest: $empty,
		onResized: $empty,
		onEmptyinit: $empty,
		reflection: 0.5,
		heightRatio: 0.458,
		offsetY: -60,//the vertical position of the images
		startIndex: 0,//start index of the images
		interval: 3000,//the speed of auto play
		factor: 115,//the distance from screen
		bgColor: '#000',
		useCaption: false,
		useResize: false,
		useSlider: false,
		useWindowResize: false,
		useMouseWheel: true,
		useKeyInput: false,
		useViewer: false
	},

	
	initialize: function(element, options){
		this.MooFlow = element; //the movieframe dom element
		this.setOptions(options); 
		this.foc = 200; //the gap between each image
		this.factor = this.options.factor; //the distance from screen
		this.offY = this.options.offsetY; //the vertical position of the images
		this.isFull = false;
		this.isAutoPlay = false;
		this.isLoading = false;
		this.inMotion = false;
		this.oneColumn = 2;
        this.batch = 20;
        this.reflectRepeatLimit = 3;
		
		//add style to this.MooFlow
		this.MooFlow.addClass('mf').setStyles({
			'overflow':'hidden',
			'background-color':this.options.bgColor,
			'position':'relative',
			'height':this.MooFlow.getSize().x*this.options.heightRatio,
			'opacity':0
		});
		if(this.options.useWindowResize) window.addEvent('resize', this.update.bind(this, 'init'));
		if(this.options.useMouseWheel || this.options.useSlider) 
		{
			var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel";
			this.MooFlow.addEvent(mousewheelevt, this.wheelTo.bind(this));
		}
		if(this.options.useKeyInput) document.addEvent('keydown', this.keyTo.bind(this));
		
		this.getElements(this.MooFlow);
	},
	
	clearInit: function(){
		//activate emptyinit process
		this.fireEvent('emptyinit');
	},
	
	//load the image data
	getElements: function(el){
		this.isLoading = true;
		this.master = {'images':[{'src':'ico/image_loader.jpg', "title":"", "href":"", "playlink":"", "duration":""}]};
		/*var els = el.getChildren();
		if(!els.length) {this.clearInit(); return;}
		// $$ returns a elements array
		$$(els).each(function(el){
			var hash = $H(el.getElement('img').getProperties('src','title','alt','longdesc'));
			if(el.get('tag') == 'a') hash.combine(el.getProperties('href','rel','target'));
			//insert hash map into master
			this.master['images'].push(hash.getClean());
			//delete the original images
			el.dispose();
		}, this);*/
		//this.clearMain();
	},
	
	//draw the gallery
	clearMain: function(){
		//this.cap means the caption of the image frame, default null
		if(this.cap){this.cap.fade(0);}
		//this.nav means the navigation of the image frame, default null
		if(this.nav){
			new Fx.Tween(this.nav, {
				'onComplete': function(){
					this.MooFlow.empty();
					this.createAniObj();
				}.bind(this)
			}).start('bottom', -50);
		}
		if(!this.nav && !this.cap){
			//make this.MooFlow empty
			this.MooFlow.empty();
			//draw the image frame
			this.createAniObj();
		}
	},
	//get the values array in master which corresponds to key
	getMooFlowElements: function(key){
		var els = [];
		this.master.images.each(function(el){ 
			els.push(el[key]); 
		});
		return els;
	},
	//build the image gallery
	createAniObj: function(){
		//aniFx is used to calculate the image position and shape when the gallery works
		this.aniFx = new Fx.Value({
			'fps': 50,//The frames per second for the transition
			'transition': Fx.Transitions.Expo.easeOut,//the effect of transition
			'link': 'cancel',//Any calls made to start while the effect is running will take precedence over the currently running transition.
			'duration': 750,//The duration of the effect in ms
			onMotion: this.process.bind(this),//when a transition motion
			'onStart': this.flowStart.bind(this),//when a transition begins
			'onComplete': this.flowComplete.bind(this)//when a transition finishes
		});
		//draw the image frame
		this.addLoader();
	},
	//draw the image frame
	addLoader: function(){
		this.MooFlow.store('height', this.MooFlow.getSize().y);
		//insert this.loader div into this.MooFlow(the circle image which means loading data)
		this.loader = new Element('div',{'class':'loader'}).inject(this.MooFlow);
        this.loader.setStyle('visibility', 'hidden');
		//The Tween effect, used to transition any CSS property of this.MooFlow from one value to another
		new Fx.Tween(this.MooFlow, {
			'duration': 800,
			//draw the images
			'onComplete': this.preloadImg.bind(this)
		}).start('opacity', 1);//set the opacity of this.MooFlow to 1
	},

	//load and show the images
	preloadImg: function(){
		this.loadedImages = new Asset.images(this.getMooFlowElements('src'), {
			//show the loaded images
			'onComplete': this.loaded.bind(this),
			//load the images
			'onProgress': this.createMooFlowElement.bind(this)
		});
	},

    loadImages: function()
    {
        if (this.preIndex == undefined)
        {
            this.preIndex = this.index;
            return;
        }
        if (this.preIndex == this.index)
        {
            this.redrawReflect();
            var i = 0;
            while (this.imagesLoaded[i + this.index * 2] && i < this.batch)
            {
                ++i;
            }
            if (i == this.batch)
            {
                return;
            }
            var start = this.index * 2 + i;
            this.loadBatch(start);
        }
        this.preIndex = this.index;
    },

    loadDetail: function()
    {
        if (this.preDetailIndex == undefined)
        {
            this.preDetailIndex = this.index;
            return;
        }
        if (this.preDetailIndex == this.index)
        {
            if (ifMovedAfterWheel == false)
            {
                var x = mouseX - $j('#scanlist').offset().left;
                var y = mouseY - $j('#scanlist').offset().top;
                if (x > 0 && x < 1000 && y > 0 && y < 458 && (x - 25) % 200 < 150 && (y < 130 && y > 30 || y < 330 && y > 230))
                {
                    var index = (this.index + Math.floor((x - 25) / 200)) * 2;
                    if (y > 230 && y < 330)
                    {
                        index++;
                    }
                    if (this.master.images[index] != undefined && this.master.images[index].title != '')
                    {
                        this.ImageMouseEnter(index, 0);
                    }
                }
            }
        }
        this.preDetailIndex = this.index;
    },

    redrawReflect: function()
    {
        var index = 2 * this.index;
        var end = 2 * this.index + 10;
        while (index < end)
        {
            if ($('images_reflect' + index) && this.reflectRepeat[index] < this.reflectRepeatLimit)
            {
                this.reflectRepeat[index]++;
                $('images_reflect' + index).destroy();
                $('imagewall_title' + index).destroy();
        		var rf = new Element('div').reflect({ 'img': this.loadedImages[index],
        		    'ref': this.options.reflection,
                    'width':100,
                    'height':100,
        			'color': this.options.bgColor
        		});
                rf.id = 'images_reflect' + index;
                rf.setStyles({'position':'absolute','left':'0px', 'top':'100px', 'width':'100%','height':'50%','background-color':this.options.bgColor}).inject($('imageitem' + index));
                new Element('div', {id:'imagewall_title' + index, 'class':'imagewall_title'}).inject($('imageitem' + index));
                var title = this.master.images[index].title.replace(/'/gi, "&apos;");
                $('imagewall_title' + index).innerHTML = "<div id='titlefont" + index +  "' title='" + title + "'>" + this.master.images[index].title  + "</div>";
                $('imagewall_title' + index).addEvents({'click':this.ImageClick.bind(this, index), 'mousedown':this.mouseDown.bind(this, index)});
            }
            index++;
        }
    },

    loadBatch: function(start)
    {
        if (this.stopLoad != 2)
        {
            return;
        }
        var i = 0;
        while (i < this.batch)
        {
            this.imagesLoaded[i + start] = true;
            i++;
        }
		var xmlhttp;
		var last = this;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				last.tempmaster = eval("(" + xmlhttp.responseText + ")");
                i = 0;
                while (i < last.tempmaster.images.length)
                {
                    var index = i + start;
                    if (last.master.images[index].title != "")
                    {
                        i++;
                        continue;
                    }
                    last.master.images[index].title = last.tempmaster.images[i].title;
                    last.master.images[index].duration = last.tempmaster.images[i].duration;
                    last.master.images[index].fav_time = last.tempmaster.images[i].fav_time;
                    last.master.images[index].href = last.tempmaster.images[i].href;
                    last.master.images[index].playlink = last.tempmaster.images[i].playlink;
                    last.master.images[index].src = last.tempmaster.images[i].src;
                    last.imagequeue.enqueue(index);
                    last.loadedImages[index] = Asset.image(last.tempmaster.images[i].src, {
                        "onLoad": function(){
                            last.loadOneImage();
                        }
                    });
                    i++;
                }
			}
		}
		xmlhttp.open("POST","getFavInfo.php",true);
		xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlhttp.send('type=1&start=' + start + "&favType=" + this.favType);
    },

    loadOneImage: function(){
        var index = this.imagequeue.dequeue();
        var last = this;
        var img = last.loadedImages[index];
        if ($('images' + index))
        {
            $('images' + index).destroy();
        }
        if ($('images_reflect' + index))
        {
            $('images_reflect' + index).destroy();
        }
        if ($('imagewall_title' + index))
        {
            $('imagewall_title' + index).destroy();
        }
        var img_background = new Element('div').inject($('imageitem' + index));
        img.id = "images" + index;
		img.setStyles({'vertical-align':'bottom', 'width':'100%', 'height':'100%'});
		//add event to each image
		img.addEvents({'click': last.ImageClick.bind(last, index), 'mousedown':this.mouseDown.bind(last, index)});
        img_background.addEvents({'mouseenter': last.ImageMouseEnter.bind(last, index, 1000), 'mouseleave': last.ImageMouseLeave.bind(last, index)});
		img.inject(img_background);
        var detail_button = new Element('div', {id:'detail_button' + index, 'class':'detail_button'}).inject(img_background);
        detail_button.addEvents({'click':last.DetailClick.bind(last, index)});
        var detail_button_content = new Element('div', {id:'detail_button_content' + index, 'class':'detailButtonContentClass'}).inject(detail_button);
        detail_button_content.innerHTML = "详情";
	    var detail_background = new Element('div', {id:'detail_background' + index, 'class':'detail_background'}).inject(img_background);
	    var detail = new Element('div', {id:'detail' + index, 'class':'detail'}).inject(img_background);
        var detail_second = new Element('div', {id:'detail_second' + index, 'class':'detailSecondClass'}).inject(detail);
        detail_second.innerHTML = "<div style='position:relative; top:10px;'>收藏于：<div style='font-weight:normal;'>" + last.master.images[index].fav_time + "</div></div>";
        var detail_first = new Element('div', {id:'detail_first' + index, 'class':'detailFirstClass'}).inject(detail);
        var detail_first_button = new Element('div', {id:'detail_first_button' + index, 'class':'detailFirstButtonClass'}).inject(detail_first);
        detail_first_button.addEvents({'click':last.CancelFavClick.bind(last, index), 'mouseenter':last.CancelFavMouseEnter.bind(last, index), 'mouseleave':last.CancelFavMouseLeave.bind(last, index), 'mousedown':last.CancelFavMouseDown.bind(last, index), 'mouseup':last.CancelFavMouseUp.bind(last, index)});
        if (favListSelectPos == user_fav_lists.length - 1)
        {
            detail_first_button.innerHTML = "<div id='detail_first_button_content' style='position:relative; top:4px; '>取消收藏</div>";
        }
        else
        {
            detail_first_button.innerHTML = "<div id='detail_first_button_content' style='position:relative; top:4px; '>移出列表</div>";
        }
		var rf = new Element('div').reflect({ 'img': last.loadedImages[index],
		    'ref': last.options.reflection,
            'width':100,
            'height':100,
			'color': last.options.bgColor
		});
        rf.id = 'images_reflect' + index;
        rf.setStyles({'position':'absolute','left':'0px', 'top':'100px', 'width':'100%','height':'50%','background-color':last.options.bgColor}).inject($('imageitem' + index));
        new Element('div', {id:'imagewall_title' + index, 'class':'imagewall_title'}).inject($('imageitem' + index));
        var title = last.master.images[index].title.replace(/'/gi, "&apos;");
        if ($('imagewall_title' + index))
        {
            $('imagewall_title' + index).innerHTML = "<div id='titlefont" + index +  "' title='" + title + "'>" + last.master.images[index].title  + "</div>";
            $('imagewall_title' + index).addEvents({'click':last.ImageClick.bind(last, index), 'mousedown':this.mouseDown.bind(last, index)});
        }
    },
	//when load the images, counter means the number of images which have been loaded, i means the index of the loaded image
	createMooFlowElement: function(counter, i){
		//get the current image obj this.master.images[i]
		var obj = this.getCurrent(i);
		//get the image
		var img = this.loadedImages[i];
		obj['width'] = img.width;
		obj['height'] = img.height;
		img.removeProperties('width','height');

		//insert obj['div'] to this.MooFlow
		obj['div'] = new Element('div').setStyles({
			'position':'absolute',
			'display':'none',
			'height': this.MooFlow.getSize().y
		}).inject(this.MooFlow);
		//insert obj['con'] to obj['div']
		obj['con'] = new Element('div', {id:'imageitem' + i}).inject(obj['div']);
		//set the initial height and width to each image, relative with the image frame
        img.id = "images" + i;
		img.setStyles({'vertical-align':'bottom', 'width':'150px', 'height':'150px'});
		//add event to each image
		//img.addEvents({'click': this.ImageClick.bind(this, i), 'dblclick': this.viewCallBack.bind(this, i)});
		img.inject(obj['con']);
		//add reflection of each image
		
		//show the loaded image number
		//this.loader.set('text', (counter) + ' / ' + this.loadedImages.length);
	},

    CancelFavMouseEnter: function(index)
    {
	    if (browser.ie)
		    $('detail_first_button' + index).style.backgroundImage = "url('ico/ImageWall/cancel_fav_mouseon.png')";
	    else
		   $('detail_first_button' + index).setStyle('background-image', 'url(ico/ImageWall/cancel_fav_mouseon.png)');	
    
    },
    CancelFavMouseLeave: function(index)
    {
	    if (browser.ie)
		    $('detail_first_button' + index).style.backgroundImage = "url('ico/ImageWall/cancel_fav.png')";
	    else
		    $('detail_first_button' + index).setStyle('background-image', 'url(ico/ImageWall/cancel_fav.png)');	
    
    },
    CancelFavMouseDown: function(index)
    {
	    if (browser.ie)
		    $('detail_first_button' + index).style.backgroundImage = "url('ico/ImageWall/cancel_fav_click.png')";
	    else
		    $('detail_first_button' + index).setStyle('background-image', 'url(ico/ImageWall/cancel_fav_click.png)');	
    },
    CancelFavMouseUp: function(index)
    {
	    if (browser.ie)
		    $('detail_first_button' + index).style.backgroundImage = "url('ico/ImageWall/cancel_fav_mouseon.png')";
	    else
		    $('detail_first_button' + index).setStyle('background-image', 'url(ico/ImageWall/cancel_fav_mouseon.png)');	
    },
	
    CancelFavClick: function(index)
    {
        var cnf;
        if (favListSelectPos == user_fav_lists.length - 1)
        {
            //cnf = confirm('确定要取消收藏么？');
            this.myConfirm('确定要取消收藏么？', index)
        }
        else
        {
            this.myConfirm('确定要移出列表么？', index);
        }
    },
    myConfirm: function(message, index)
    {
        var last = this;
        ifCancelFav = false;
    	$("page_background_regist_filter").setStyle("visibility", "visible");
    	$('page_background_regist_filter').set('opacity', 0.8);
    	$("page_background_regist").setStyle("visibility", "visible");
        this.emailActivate = new Element('div', {id:"emailActivate"}).addClass('emailActivateClass').inject($("page_background_regist"));
        this.emailActivate.first = new Element('div', {id:"registPanel_first"}).addClass('registPanel_firstClass').inject(this.emailActivate);
        this.emailActivate.first.closebutton_background = new Element('div', {id:"registPanel_first_closebutton_background"}).addClass('registPanel_first_closebutton_backgroundClass').inject(this.emailActivate.first);
        this.emailActivate.first.closebutton_background.innerHTML = "<img src='ico/login_reg/login_close_normal.png' id='regist_close' onclick='clearregist(this)' onmouseover='closeregistMouseOver(this)' onmouseout='closeregistMouseOut(this)' onmousedown='closeregistMouseDown(this)' onmouseup='closeregistMouseUp(this)' />";
        this.emailActivate.logo = new Element('div').addClass('changePass_logoClass').inject($(this.emailActivate));
        this.emailActivate.logo.innerHTML = "<img src='ico/logo4.png' />";
        this.emailActivate.second = new Element('div', {id:'emailActivate_second'}).addClass('warningClass').inject($(this.emailActivate));
        this.emailActivate.second.content = new Element('div', {id:'confirm_message'}).addClass('confirmMessageClass').inject($(this.emailActivate.second));
        this.emailActivate.second.content.innerHTML = "<span style='color:#999'>" + message + "</span>";
        this.emailActivate.third = new Element('div', {id:'emailActivate_third'}).addClass('confirmThirdClass').inject($(this.emailActivate));
    	this.emailActivate.third.innerHTML = "<div id='cancelFavConfirm' class='deleteFavListConfirmClass' onmouseover='loginButtonMouseOver(this)' onmouseout='loginButtonMouseOut(this)' onmousedown='loginButtonMouseDown(this)' onmouseup='loginButtonMouseUp(this)'><div style='position:relative; top:10px'>确定</div></div>";
        $('cancelFavConfirm').addEvents({'click':last.cancelFav.bind(last, index)});
    },

    cancelFav: function(index)
    {
        $('imageitem' + index).set('tween', {duration: 1000});
        $('imageitem' + index).tween('opacity', 0);
        last = this;
        setTimeout(function(){
            $('imageitem' + index).set('visibility', 'hidden');
            last.master.images[index].title = '';
        }, 1000);
		var xmlhttp;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.open("POST",'cancelFav.php',true);
		xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlhttp.send('videoID=' + this.master.images[index].href + '&listname=' + user_fav_lists[favListSelectPos]);
	    if ($('regist_close'))
	    {
		    clearregist($('regist_close'));	
	    }
    },
	ImageClick: function(index)
	{
        if (this.master.images[index].title == "")
        {
            return;
        }
		watchmovie(this.master.images[index].href, this.master.images[index].title, this.master.images[index].playlink);
        watch_movie_image_source = this.master.images[index].src;
	},
    //mouse down on the index image
    mouseDown: function(index)
    {
        var last = this;
        if (this.master.images[index].title == "")
        {
            return;
        }
        setTimeout(function(){last.checkDrag(index)}, 200);
    },
    //check if dragging the indexed image
    checkDrag: function(index)
    {
        if (!ifWatchMovie)
        {
            videoID = this.master.images[index].href;
            move = true;
            showDragImg(this.master.images[index].src);
        }
    },

    DetailClick: function(index)
    {
        if ($('detail_button_content' + index).innerHTML == "详情")
        {
            $('detail_button_content' + index).innerHTML = "收起";
            $j('#detail_button' + index).css('height', '130px');
            $('detail_background' + index).set('visibility', '');
            $('detail_background' + index).set('tween', {duration: 500});
		    $('detail_background' + index).tween('opacity', 0.6);
            $('detail' + index).set('visibility', '');
            $('detail' + index).set('tween', {duration: 500});
		    $('detail' + index).tween('opacity', 1);
        }
        else
        {
            $('detail_button_content' + index).innerHTML = "详情";
            $('detail_background' + index).set('visibility', 'hidden');
            $('detail_background' + index).set('tween', {duration: 1});
            $('detail_background' + index).tween('opacity', 0);
            $('detail' + index).set('visibility', 'hidden');
            $('detail' + index).set('tween', {duration: 1});
            $('detail' + index).tween('opacity', 0);
        }
    },

    ImageMouseEnter: function(index, delay)
    {
        if (this.master.images[index] == undefined || this.master.images[index].title == "")
        {
            return;
        }
        if (delay == undefined)
        {
            delay = 1000;
        }
        this.detailIndex = index;
        if ($j('#detail_background' + index).css('visibility') == 'hidden')
        {
            if (checkInFavList())
            {
                return;
            }
            if (ifWatchMovie)
            {
                return;
            }
            $('detail_button' + index).set('visibility', '');
            $('detail_button' + index).set('tween', {duration: 100});
		    $('detail_button' + index).tween('opacity', 1);
        }
    },
    ImageMouseLeave: function(index)
    {
        if (this.master.images[index] == undefined || this.master.images[index].title == "")
        {
            return;
        }
        this.detailIndex = undefined;
        //clearTimeout(this.detailNumber);
        $('detail_button_content' + index).innerHTML = "详情";
        $('detail_background' + index).set('visibility', 'hidden');
        $('detail_background' + index).set('tween', {duration: 1});
        $('detail_background' + index).tween('opacity', 0);
        $('detail' + index).set('visibility', 'hidden');
        $('detail' + index).set('tween', {duration: 1});
        $('detail' + index).tween('opacity', 0);
        $('detail_button' + index).set('visibility', 'hidden');
        $('detail_button' + index).set('tween', {duration: 1});
        $('detail_button' + index).tween('opacity', 0);
    },
	//after loading all the images, draw them
	loaded: function(){
        if (this.stopLoad == 3)
        {
            return;
        }
        last = this;
        last.check = setInterval(function(){last.loadImages()}, 1000);
        last.checkdetail = setInterval(function(){last.loadDetail()}, 1000);
        ifMovedAfterWheel = false;
        this.stopLoad = 1;
        var last = this;
        setTimeout(function(){last.loadOver()}, 1000);
		this.index = this.options.startIndex; //the image index which is in the center
		this.iL = Math.ceil(this.master.images.length / this.oneColumn) - 5; //image number minus 1
        if (this.iL < 0)
        {
            this.iL = 0;
        }
        iL = this.iL;
		//clear this.loader
		new Fx.Tween(this.loader, {
			'duration': 800,
			//draw the images
			'onComplete': this.createUI.bind(this)
		}).start('opacity', 0);
	},
    loadOver: function()
    {
        this.stopLoad = 2;
    },
	//draw the image frame
	createUI: function(){
		//clear this.loader
		this.loader.dispose();
		//if have caption, draw it
		if(this.options.useCaption){
			this.cap = new Element('div').addClass('caption').set('opacity',0).inject(this.MooFlow);
		}
		//add the navigation bar to this.MooFlow
		this.nav = new Element('div').addClass('mfNav').setStyle('bottom','-50px');
		//auto play icon
		this.autoPlayCon = new Element('div').addClass('autoPlayCon');
		//slider con
		this.sliderCon = new Element('div').addClass('sliderCon');
		//resize con
		this.resizeCon = new Element('div').addClass('resizeCon');		
		if(this.options.useAutoPlay){
			this.autoPlayCon.adopt(
				new Element('a',{'class':'stop','events': {'click':this.stop.bind(this)}}), 
				new Element('a',{'class':'play','events': {'click':this.play.bind(this)}})
			);
		}
		if(this.options.useSlider){
			//pre icon
			this.sliPrev = new Element('a',{'class':'sliderNext','events': {'click':this.prev.bind(this)}});
			//next icon
			this.sliNext = new Element('a',{'class':'sliderPrev','events': {'click':this.next.bind(this)}});
			this.knob = new Element('div',{id:'knob', 'class':'knob'});
            this.knob.left = new Element('div',{'class':'knobleft'});
			this.knob.adopt(this.knob.left);
			//the slider
			this.slider = new Element('div',{'class':'slider'}).adopt(this.knob);
			//add pre, slider, next icons into sliderCon
			this.sliderCon.adopt(this.sliPrev,this.slider,this.sliNext);
			this.slider.store('parentWidth', this.sliderCon.getSize().x-this.sliPrev.getSize().x-this.sliNext.getSize().x);
		}
		if(this.options.useResize){
			this.resizeCon.adopt(new Element('a',{'class':'resize','events': {'click':this.setScreen.bind(this)}}));
		}	
		//add these three icons into this.MooFlow	
		this.MooFlow.adopt(this.nav.adopt(this.autoPlayCon, this.sliderCon, this.resizeCon));	
		//draw the images and tool bar
		this.showUI();
	},
	//draw the images and tool bar
	showUI: function(){
		//fade in the caption
		if(this.cap) this.cap.fade(1);
		//nav from -50 to 20, dynamic
		this.nav.tween('bottom', 20);
		//activate event start, seems no use here
		this.fireEvent('start');
		this.update();
	},
	//draw the images and tool bar
	update: function(e){
		if(e == 'init') return;
		//this.oW = MooFlow's width
		this.oW = this.MooFlow.getSize().x;
		this.sz = this.oW * 0.5;
		if(this.options.useSlider){	
			//set the width of the slider
			this.slider.setStyle('width',this.slider.getParent().getSize().x-this.sliPrev.getSize().x-this.sliNext.getSize().x-1);
			//set the width of the slider knob
            knobWidth = (this.slider.getSize().x * 1.0 / (this.iL + 1));
			this.knob.setStyle('width',(this.slider.getSize().x * 1.0 / (this.iL + 1)));
            if (this.knob.getSize().x < 16)
            {
                this.knob.left.destroy();
                this.knob.setStyle('background', 'url()');
                this.knob.cover = new Element('img').inject(this.knob, 'top');
	            this.knob.cover.src = "skin/slider.png";
                this.knob.cover.setStyles({
                    'position':'absolute',
                    'top':'0px',
                    'left':'-5px',
                    //'width': this.knob.getSize().x + "px",
                    'width': "16px",
                    'height':'14px'
                });
            }
			//create the slider object, and set index
			this.sli = new SliderEx1(this.slider, this.knob, {steps: this.iL}).set(this.index);
			//when slider changes, the images should also change
            if (this.iL > 0)
            {
			    this.sli.addEvent('onChange', this.glideTo.bind(this));
            }
		}
		//change images according to the index
		this.glideTo(this.index);
		this.isLoading = false;
	},
	//used in resize
	setScreen: function(){
		if(this.isFull = !this.isFull){
			this.holder = new Element('div').inject(this.MooFlow,'after');
			this.MooFlow.wraps(new Element('div').inject(document.body));
			this.MooFlow.setStyles({'position':'absolute','z-index':'100','top':'0','left':'0','width':window.getSize().x,'height':window.getSize().y});
			if(this.options.useWindowResize){
				this._initResize = this.initResize.bind(this);
				window.addEvent('resize', this._initResize);
			}
		} else {
			this.MooFlow.wraps(this.holder);
			window.removeEvent('resize', this._initResize);
			delete this.holder, this._initResize;
			this.MooFlow.setStyles({'position':'relative','z-index':'','top':'','left':'','width':'','height':this.MooFlow.retrieve('height')});
			this.slider.setStyle('width',this.slider.retrieve('parentWidth'));
		}
		this.fireEvent('resized', this.isFull);
		this.update();
	},
	//used in resize
	initResize: function(){
		this.MooFlow.setStyles({'width':window.getSize().x,'height':window.getSize().y});
		this.update();
	},
	//get current index
	getCurrent: function(index){
		return this.master.images[$chk(index) ? index : this.index];
	},
	
	loadJSON: function(url){
		if(!url || this.isLoading) return;
		this.isLoading = true;
		new Request.JSON({
			'onComplete': function(data){
				if($chk(data)){
					this.master = data;
					this.clearMain();
					this.fireEvent('request', data);
				}
			}.bind(this)
		}, this).get(url);
	},

    //stopLoad == undefined means images have not been loaded
    //stopLoad == 1 means images have been loaded but not shown
    //stopLoad == 2 means images have been loaded and show
    //stopLoad == 3 means images have not been loaded and be stoped
    stopLoading: function() {
        this.stopCheck();
        if (this.stopLoad != undefined)
        {
            return;
        }
        this.stopLoad = 3;
    },

    ifStopLoading: function() {
        if (!this.imagequeue.isEmpty())
        {
            return 1;
        }
        return this.stopLoad;
    },
	
	loadData: function(url, favType){
        this.favType = favType;
        if (url == 'getFavInfo.php')
        {
            this.watchType = 4;
        }
		this.isLoading = true;
		var xmlhttp;
		var last = this;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
                var count = parseInt(xmlhttp.responseText);
                var s = '{"images":[';
                var i = 1;
                last.imagesLoaded = [];
                last.imagequeue = new Queue();
                last.imagesLoaded.push(false);
                last.reflectRepeat = [];
                last.reflectRepeat.push(0);
                while (i < count)
                {
                    ++i;
                    last.imagesLoaded.push(false);
                    last.reflectRepeat.push(0);
                    s += '{"src":"ico/loading-gif-animation.gif", "title":"", "href":"", "playlink":"", "duration":""},';
                }
                if (count > 0)
                {
                    s += '{"src":"ico/loading-gif-animation.gif", "title":"", "href":"", "playlink":"", "duration":""}';
                }
                s += ']}';
				last.master = eval("(" + s + ")");
				last.clearMain();
			}
		}
		xmlhttp.open("POST",url,true);
		xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
		xmlhttp.send('type=0&favType=' + favType);
	},

    stopCheck: function()
    {
        clearInterval(this.check);
        clearInterval(this.checkdetail);
    },
	
	loadHTML: function(url, filter){
		if(!url || !filter || this.isLoading) return;
		this.isLoading = true;
		new Request.HTML({
			'onSuccess': function(tree, els, htm){
				var result = new Element('div', {'html': htm}).getChildren(filter);
				this.getElements(result);
				this.fireEvent('request', result);
			}.bind(this)
		}, this).get(url);
	},
	
	flowStart: function(){
		this.inMotion = true;
	},
	
	flowComplete: function(){
		this.inMotion = false;
	},
	//no use
	viewCallBack: function(index){
		if(this.index != index || this.inMotion) return;
		var el = $H(this.getCurrent());
		var returnObj = {};
		returnObj['coords'] = el.div.getElement('img').getCoordinates();
		el.each(function(v, k){
			if($type(v) == 'number' || $type(v) == 'string') returnObj[k] = v;
		}, this);
		this.fireEvent('clickView', returnObj);
	},
	//pre icon
	prev: function(){
		if(this.index > 0) this.clickTo(this.index-1);
	},
	//next icon
	next: function(){
		if(this.index < this.iL) this.clickTo(this.index+1);
	},
	//stop autoplay
	stop: function(){
		$clear(this.autoPlay);
		this.isAutoPlay = false;
		this.fireEvent('autoStop');
	},
	//auto play
	play: function(){
		//auto play, use this.auto and the interval is this.options.interval
		this.autoPlay = this.auto.periodical(this.options.interval, this);
		this.isAutoPlay = true;
		this.fireEvent('autoPlay');
	},
	auto: function(){
		if(this.index < this.iL) this.next();
		else if(this.index == this.iL) this.clickTo(0);
	},
	//keyboeard action
	keyTo: function(e){
		if (!this.isLoading)
		{
			switch (e.code){
				case 37: e.stop(); this.prev();	break;
				case 39: e.stop(); this.next();
			}
		}
	},
	//mouse wheel action
	wheelTo: function(e){
		if (!this.isLoading)
		{
			if(e.wheel > 0) this.prev();
			if(e.wheel < 0) this.next();
			e.stop().preventDefault();
		}
	},
	//click to the index image
	clickTo: function(index){
		/*this.aniFx.cancel();*/
		if(this.sli) this.sli.set(index);
		this.glideTo(index);
	},
	//draw the images, dynamically set index as the center
	glideTo: function(index){
        /*if ($('refresh'))
        {
            $('refresh').destroy();
        }*/
        ifMovedAfterWheel = false;
        this.ImageMouseLeave(this.detailIndex);
		this.index = index;
		//begin a transition, from this.aniFx.get() to index*(-this.foc)
		this.aniFx.start(this.aniFx.get(), index*(-this.foc));
		//draw the current caption
		if(this.cap) 
        {
        }
	},
	//calculate the new position and shape for each image
	process: function(x){
		//zI = this.iL = image number - 1
		//foc = this.foc means distance between images
		//f = this.factor means the distance from screen
		//sz means the half of image frame width
		//oW means image frame width
		//offY means the vertical position of the images
		var z,W,H,zI=this.iL,foc=this.foc,f=this.factor,sz=this.sz,oW=this.oW,offY=this.offY,div,elh,elw;
		//draw each image
		var k = 0;
		this.master.images.each(function(el){
			div = el.div.style;
			//at most 11 images can be seen in the image frame
			div.cursor = 'pointer';	
			div.left =  (x + 25) + 'px';
			if (x > foc * -1 && x < foc * 5)
			{
				if (k % 2 == 0)
				{
					div.top = '30px';
				}
				else
				{
					div.top = '230px';
					x += foc;
				}
				//change the height of each image
				div.height = '100px';
				//change the width of each image		
				div.width = '150px';
				div.display = 'block';
			}
			else
			{
				if (k % 2 != 0)
				{
					x += foc;
				}
				div.display = 'none';
			}
			k++;
		});
	}
});
//define SliderEx1
/*var SliderEx1 = new Class({
	Extends: Slider,
	//set the step
	set: function(step){
		this.step = Math.round(step);
		//tick: display an effect of the knob moving to the desired position
		this.fireEvent('tick', this.toPosition(this.step));
		return this;
    },
	//when click to slider(not pre, next icons)
	clickedElement: function(event){
		var dir = this.range < 0 ? -1 : 1;
		var position = event.page[this.axis] - this.element.getPosition()[this.axis] - this.half;
		position = position.limit(-this.options.offset, this.full -this.options.offset);
		this.step = Math.round(this.min + dir * this.toStep(position));
		this.fireEvent('tick', position);
	}
});*/
var SliderEx1 = new Class({
	Extends: Slider,
	//set the step
	set: function(step){
		this.step = Math.round(step);
		//tick: display an effect of the knob moving to the desired position
		this.fireEvent('tick', this.toPosition(this.step));
		return this;
    },
	//when click to slider(not pre, next icons)
	clickedElement: function(event){
		var dir = this.range < 0 ? -1 : 1;
        //this.half is the half of knob's width
		var position = event.page[this.axis] - this.element.getPosition()[this.axis];
		//position = position.limit(-this.options.offset, this.full -this.options.offset);
		//this.step = Math.floor(position / (this.half * 2));
		this.step = Math.floor(position / knobWidth);
        if (this.step > iL)
        {
            this.step = iL;
        }
		this.checkStep();
		this.fireEvent('tick', this.toPosition(this.step));
	}
});

//define Fx.Value which Extends Fx, calculate the position and shape of images when motion happens
/*Fx.Value = new Class({
	Extends: Fx,
	//this function will be called several times in a transition, the repeat time depends on the Fx.duration
	compute: function(from, to, delta){
		//calculate the x position of the first image
		this.value = Fx.compute(from, to, delta);//(to - from) * delta + from; calculate the real move distance
		//Fires(activate) all events of the motion type in the Class instance, this.value is the argument to motion.
		//when stablized, this.value = this.foc
		this.fireEvent('motion', this.value);
		return this.value;
	},
	get: function(){
		return this.value || 0;
	}
});*/

//create a reflection to an image
/*Element.implement({
	reflect: function(arg){
        var i = arg.img.clone().set('src', arg.img.src); // this works in mootools whose version is larger than 1.2.1
		if(Browser.Engine.trident){
			i.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=20, style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy='+100*arg.ref+')';
			i.setStyles({'width':'100%', 'height':'100%'});
			return new Element('div').adopt(i);
		} else {
			var can = new Element('canvas').setProperties({'width':arg.width, 'height':arg.height});
			if(can.getContext){
				var ctx = can.getContext("2d");
				ctx.save();
				ctx.translate(0,arg.height-1);
				ctx.scale(1,-1);
				ctx.drawImage(i, 0, 0, arg.width, arg.height);
				ctx.restore();
				ctx.globalCompositeOperation = "destination-out";
				ctx.fillStyle = arg.color;
				ctx.fillRect(0, arg.height*0.5, arg.width, arg.height);
				var gra = ctx.createLinearGradient(0, 0, 0, arg.height*arg.ref);					
				gra.addColorStop(1, "rgba(255, 255, 255, 1.0)");
				gra.addColorStop(0, "rgba(255, 255, 255, "+(1-arg.ref)+")");
				ctx.fillStyle = gra;
				ctx.rect(0, 0, arg.width, arg.height);
				ctx.fill();
				delete ctx, gra;
			}
			return can;
		}
	}
});*/

/*window.addEvent('domready', function(){
	$$('.MooFlowieze').each(function(mooflow){
		new MooFlow(mooflow);
	});
});*/
